package xj.toolkit.netty.initializer;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import xj.toolkit.netty.handler.codec.http.HttpResponseHandler;
import xj.toolkit.netty.handler.codec.http.ssl.HttpSslContextFactory;

import javax.net.ssl.SSLEngine;

public class HttpClientInitializer extends SslBaseInitializer {

	private HttpResponseHandler httpResponseHandler;

	private ChannelHandler nettyEncoder;
	private ChannelHandler nettyDecoder;

	// 一个HTTP传输的最大数据量,默认1G
	private int maxContentLength = 1024 * 1024 * 1024;
	// Raises a ReadTimeoutException when no data was read within a certain
	// period of time.
	private int readTimeoutSeconds = 0;

	private HttpSslContextFactory httpSslContextFactory;

	@Override
	public void addCodecHandler(ChannelPipeline pipeline) throws Exception {
		if (super.isUseSsl()) {
			SSLEngine engine = httpSslContextFactory.getClientSslContext().newEngine(pipeline.channel().alloc());
			engine.setUseClientMode(true);
			pipeline.addLast("ssl", new SslHandler(engine));
		}
		if (readTimeoutSeconds > 0) {
			pipeline.addLast(new ReadTimeoutHandler(readTimeoutSeconds));
		}
		pipeline.addLast("codec", new HttpClientCodec()).addLast("aggregator",
				new HttpObjectAggregator(maxContentLength));
		if (nettyEncoder != null) {
			pipeline.addLast("nettyEncoder", nettyEncoder);
		}
		if (nettyDecoder != null) {
			pipeline.addLast("nettyDecoder", nettyDecoder);
		}
	}

	@Override
	protected void addBusinessHandler(ChannelPipeline pipeline) throws Exception {
		pipeline.addLast("handler", httpResponseHandler);
	}

	public void setHttpResponseHandler(HttpResponseHandler httpResponseHandler) {
		this.httpResponseHandler = httpResponseHandler;
	}

	public void setNettyEncoder(ChannelHandler nettyEncoder) {
		this.nettyEncoder = nettyEncoder;
	}

	public void setNettyDecoder(ChannelHandler nettyDecoder) {
		this.nettyDecoder = nettyDecoder;
	}

	public void setMaxContentLength(int maxContentLength) {
		this.maxContentLength = maxContentLength;
	}

	public int getReadTimeoutSeconds() {
		return readTimeoutSeconds;
	}

	public void setReadTimeoutSeconds(int readTimeoutSeconds) {
		this.readTimeoutSeconds = readTimeoutSeconds;
	}
}
